package java8.future;

import org.junit.Test;

import java.util.Optional;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @program JavaBase
 * @description:
 * @author: zhanglu
 * @create: 2020-03-02 07:42:00
 */
public class CompletableFuntureInAction01 {

    private final static Random random = new Random(System.currentTimeMillis());

    @Test
    public void test01() throws ExecutionException, InterruptedException {
        CompletableFuture<Object> completableFuture = new CompletableFuture<>();
        new Thread(() -> {
            double value = get();
            completableFuture.complete(value);
        }).start();

        System.out.println("111");

        //类似于funture.get
//        Optional.ofNullable(completableFuture.get()).ifPresent(x -> System.out.println(x));
//        System.out.println("222");

        completableFuture.whenComplete((v, t) -> {
            Optional.ofNullable(v).ifPresent(System.out::println);
            Optional.ofNullable(t).ifPresent(e -> e.printStackTrace());
        });

        System.out.println("333");

        while (true){

        }

    }

    public static double get(){
        double v = 0d;
        try {
            Thread.sleep(new Random().nextInt(1000));
            v = random.nextDouble();
            System.out.println(v);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return v;
    }

}
